//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends eui.UILayer {


    protected createChildren(): void {
        super.createChildren();
        egret.ImageLoader.crossOrigin = "anonymous";
        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin
        })

        egret.lifecycle.onPause = () => {
            egret.ticker.pause();
        }

        egret.lifecycle.onResume = () => {
            egret.ticker.resume();
        }

        //inject the custom material parser
        //注入自定义的素材解析器
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());

        this.runGame().catch(e => {
            console.log(e);
        })
    }

    private async runGame() {
        await this.loadResource()
        await platform.login();
        const userInfo = await platform.getUserInfo();
        
        Dispatcher.ins.addEventListener("login", this.createGameScene , this);//完成登录后（可以改成socket链接完成以后再进入场景解析）

        //进行登录
        if(location.href.indexOf("?") !== -1){
           http.getHttpServer("login");
        }else{
            if(location.href.indexOf("127.0.0.1") !== -1){
                location.href = location.href + "?code=123456&areaId=1000&gameId=2001";
            }
        }
    }

    private async loadResource() {
        try {
            // await RES.loadConfig("default.res.json?v=1524551590", "resource/");
            // if(location.href.indexOf("h5-pre.farm.pk0818.com") !== -1){
            //     await RES.loadConfig("asset.res.json?v=1525229517", "https://17pkmj.image.alimmdn.com/2001/resource/");
            // }else{
                await RES.loadConfig("default.res.json?v=1524551595", "resource/");
            // }
            
            await this.loadTheme();
            await RES.loadGroup("loading",1);
            this.loadingView = new LoadingUI();
            this.stage.addChild(this.loadingView);
            await RES.loadGroup("preload", 0, this.loadingView);
            // this.stage.removeChild(loadingView);
        }
        catch (e) {
            console.error(e);
        }
    }

    private loadTheme() {
        return new Promise((resolve, reject) => {
            // load skin theme configuration file, you can manually modify the file. And replace the default skin.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            let theme:any;
            // if(location.href.indexOf("h5-pre.farm.pk0818.com") !== -1){
            //     EXML.prefixURL = "https://17pkmj.image.alimmdn.com/2001/";
            //     theme = new eui.Theme("https://17pkmj.image.alimmdn.com/2001/resource/asset.thm.json?v=1525229517", this.stage);     
            // }else{
                theme = new eui.Theme("resource/default.thm.json?v=1524551595", this.stage);
            // }
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);
        })
    }

    private loadingView:LoadingUI;
    private myHome:myHome;
    private label:egret.TextField;
    /**
     * 创建场景界面
     * Create scene interface
     */
    protected async createGameScene(){
        common.stageW = this.stage.stageWidth;
        common.stageH = this.stage.stageHeight;

        this.stage.removeChild(this.loadingView);
        this.myHome = new myHome();
        this.stage.addChild(this.myHome);

        //显示信息的label
        // this.label = new egret.TextField();
        // this.label.x = common.stageW / 2;
        // this.stage.addChild(this.label);
        // this.label.size = 20;
        // this.label.fontFamily = "楷体";
        // this.label.text = "暂未获取到经纬度信息";
        // this.label.anchorOffsetX = this.label.width / 2;

        // var gps = new egret.Geolocation();
        // //监听经纬度变化的事件
        // gps.addEventListener(egret.Event.CHANGE,this.onGotLocation,this);
        // //开始监听变化
        // gps.start();
    }

    //获取地理位置信息
    private onGotLocation(e:egret.GeolocationEvent){
        this.label.text = "当前位置:"+e.latitude.toFixed(1)+","+e.longitude.toFixed(1);
        // console.log(e.latitude);//纬度
        // console.log(e.longitude);//经度
    }
}
